{% extends "base.html" %}
{% block content %}
<div class="container mt-4 main-content">
    <!-- 标题和添加按钮 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="mb-0">
            <i class="bi bi-people-fill me-2"></i>用户列表
        </h2>
        <a href="{{ url_for('add_user') }}" class="btn btn-primary">
            <i class="bi bi-person-plus-fill me-1"></i>添加用户
        </a>
    </div>

    <!-- 搜索框 -->
    <div class="card mb-4">
        <div class="card-body">
            <form class="row g-3" method="GET">
                <div class="col-md-6 col-lg-4">
                    <div class="input-group">
                        <span class="input-group-text">
                            <i class="bi bi-search"></i>
                        </span>
                        <input type="text" 
                               class="form-control" 
                               name="search" 
                               placeholder="搜索用户名或邮箱..." 
                               value="{{ request.args.get('search', '') }}"
                               autocomplete="off">
                        {% if request.args.get('search') %}
                        <a href="{{ url_for('index') }}" class="btn btn-outline-secondary">
                            <i class="bi bi-x-lg"></i>
                        </a>
                        {% endif %}
                    </div>
                </div>
                <div class="col-auto">
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-search me-1"></i>搜索
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- 搜索和排序状态提示 -->
    <div class="d-flex justify-content-between align-items-center mb-3">
        {% if request.args.get('search') %}
        <div class="alert alert-info mb-0" role="alert">
            <i class="bi bi-info-circle me-2"></i>
            找到 {{ total_users }} 个匹配的用户
        </div>
        {% else %}
        <div></div>
        {% endif %}
        
        <div class="text-muted">
            <i class="bi bi-sort-down me-1"></i>
            当前排序: {{ 'ID' if sort_by == 'id' else ('用户名' if sort_by == 'username' else '邮箱') }}
            ({{ '升序' if order == 'asc' else '降序' }})
        </div>
    </div>

    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
        {% if users %}
        <table class="table table-striped table-hover align-middle">
            <thead class="table-light">
                                            <tr>
                                                <th>
                                                    <a href="{{ url_for('index', sort='id', order=('desc' if sort_by == 'id' and order == 'asc' else 'asc'), search=request.args.get('search', '')) }}" 
                                                       class="text-decoration-none text-dark">
                                                        ID
                                                        {% if sort_by == 'id' %}
                                                            <i class="bi bi-caret-{% if order == 'asc' %}up{% else %}down{% endif %}-fill"></i>
                                                        {% endif %}
                                                    </a>
                                                </th>
                                                <th>
                                                    <a href="{{ url_for('index', sort='username', order=('desc' if sort_by == 'username' and order == 'asc' else 'asc'), search=request.args.get('search', '')) }}" 
                                                       class="text-decoration-none text-dark">
                                                        用户名
                                                        {% if sort_by == 'username' %}
                                                            <i class="bi bi-caret-{% if order == 'asc' %}up{% else %}down{% endif %}-fill"></i>
                                                        {% endif %}
                                                    </a>
                                                </th>
                                                <th>
                                                    <a href="{{ url_for('index', sort='email', order=('desc' if sort_by == 'email' and order == 'asc' else 'asc'), search=request.args.get('search', '')) }}" 
                                                       class="text-decoration-none text-dark">
                                                        邮箱
                                                        {% if sort_by == 'email' %}
                                                            <i class="bi bi-caret-{% if order == 'asc' %}up{% else %}down{% endif %}-fill"></i>
                                                        {% endif %}
                                                    </a>
                                                </th>
                                                <th class="text-end">操作</th>
                                            </tr>
            </thead>
            <tbody>
                {% for user in users %}
                <tr>
                    <td>{{ user.id }}</td>
                    <td>
                        <i class="bi bi-person-circle me-2"></i>
                        {{ user.username }}
                    </td>
                    <td>
                        <i class="bi bi-envelope me-2"></i>
                        {{ user.email }}
                    </td>
                    <td class="text-end">
                        <a href="{{ url_for('edit_user', user_id=user.id) }}"
                            class="btn btn-outline-warning btn-sm me-1">
                            <i class="bi bi-pencil-square"></i>
                            编辑
                        </a>
                        <button type="button" class="btn btn-outline-danger btn-sm"
                            data-delete-url="{{ url_for('delete_user', user_id=user.id) }}"
                            onclick="confirmDelete(this)">
                            <i class="bi bi-trash"></i>
                            删除
                        </button>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
        {% else %}
        <div class="text-center py-5">
            <i class="bi bi-inbox text-muted" style="font-size: 3rem;"></i>
            <h3 class="mt-3 text-muted">没有用户数据。</h3>
            {% if request.args.get('search') %}
            <p class="text-muted">没有找到匹配的搜索结果</p>
            <a href="{{ url_for('index') }}" class="btn btn-outline-primary mt-2">
                <i class="bi bi-arrow-left me-1"></i>返回所有用户
            </a>
            {% else %}
            <p class="text-muted">点击下方按钮添加新用户</p>
            <a href="{{ url_for('add_user') }}" class="btn btn-primary mt-2">
                <i class="bi bi-plus-circle me-1"></i>添加用户
            </a>
            {% endif %}
        </div>
        {% endif %}
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header border-bottom-0">
                <h5 class="modal-title" id="deleteModalLabel">
                    <i class="bi bi-exclamation-triangle-fill text-danger me-2"></i>确认删除
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body text-center py-4">
                <div class="mb-4">
                    <i class="bi bi-trash text-danger" style="font-size: 4rem;"></i>
                </div>
                <h4 class="mb-3">确定要删除这个用户吗？</h4>
                <p class="text-muted mb-0">
                    <i class="bi bi-info-circle me-1"></i>
                    此操作无法撤销，用户数据将被永久删除。
                </p>
            </div>
            <div class="modal-footer border-top-0 justify-content-center gap-2">
                <button type="button" class="btn btn-outline-secondary px-4" data-bs-dismiss="modal">
                    <i class="bi bi-x-lg me-1"></i>取消
                </button>
                <a href="#" class="btn btn-danger px-4" id="confirmDeleteBtn">
                    <i class="bi bi-trash me-1"></i>确定删除
                    <span class="spinner-border spinner-border-sm ms-1 d-none" role="status" aria-hidden="true"></span>
                </a>
            </div>
        </div>
    </div>
</div>

<script>
    // 确保DOM和Bootstrap都加载完成
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化变量
        let deleteModal;
        let modalElement = document.getElementById('deleteModal');
        let confirmBtn = document.getElementById('confirmDeleteBtn');

        // 确保模态框元素存在
        if (modalElement && confirmBtn) {
            try {
                // 初始化模态框
                deleteModal = new bootstrap.Modal(modalElement);
                
                // 删除确认函数
                window.confirmDelete = function(button) {
                    if (!button) return;
                    
                    // 获取删除URL
                    const deleteUrl = button.getAttribute('data-delete-url');
                    if (!deleteUrl) {
                        console.error('No delete URL provided');
                        return;
                    }

                    // 设置确认按钮的URL
                    confirmBtn.href = deleteUrl;

                    // 显示模态框
                    deleteModal.show();
                };

                // 点击确认删除按钮时显示加载状态
                confirmBtn.addEventListener('click', function(e) {
                    const spinner = this.querySelector('.spinner-border');
                    const icon = this.querySelector('.bi-trash');
                    if (spinner && icon) {
                        spinner.classList.remove('d-none');
                        icon.classList.add('d-none');
                        this.classList.add('disabled');
                    }
                });

                // 监听模态框关闭事件
                modalElement.addEventListener('hidden.bs.modal', function () {
                    // 重置按钮状态
                    const spinner = confirmBtn.querySelector('.spinner-border');
                    const icon = confirmBtn.querySelector('.bi-trash');
                    if (spinner && icon) {
                        spinner.classList.add('d-none');
                        icon.classList.remove('d-none');
                        confirmBtn.classList.remove('disabled');
                    }
                    confirmBtn.href = '#';
                });

            } catch (e) {
                console.error('Error initializing modal:', e);
                // 降级处理：使用原生confirm
                window.confirmDelete = function(button) {
                    if (!button) return;
                    const deleteUrl = button.getAttribute('data-delete-url');
                    if (deleteUrl && confirm('确定要删除这个用户吗？此操作无法撤销。')) {
                        window.location.href = deleteUrl;
                    }
                };
            }
        }

        // 自动隐藏提示消息
        const alerts = document.querySelectorAll('.alert:not(.alert-info)');
        if (alerts.length > 0) {
            setTimeout(function() {
                alerts.forEach(function(alert) {
                    try {
                        const bsAlert = new bootstrap.Alert(alert);
                        bsAlert.close();
                    } catch (e) {
                        alert.style.display = 'none';
                    }
                });
            }, 3000);
        }
    });
</script>

<script>
    // 确保DOM和Bootstrap都加载完成
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化变量
        let deleteModal;
        let modalElement = document.getElementById('deleteModal');

        // 确保模态框元素存在
        if (modalElement) {
            try {
                // 尝试初始化模态框
                deleteModal = new bootstrap.Modal(modalElement);
                
                // 删除确认函数
                window.confirmDelete = function(button) {
                    if (!button) return;
                    
                    // 获取删除URL
                    const deleteUrl = button.getAttribute('data-delete-url');
                    if (!deleteUrl) {
                        console.error('No delete URL provided');
                        return;
                    }

                    // 设置确认按钮的URL
                    const confirmBtn = document.getElementById('confirmDeleteBtn');
                    if (confirmBtn) {
                        confirmBtn.href = deleteUrl;
                    }

                    // 显示模态框
                    deleteModal.show();
                };

                // 监听模态框关闭事件
                modalElement.addEventListener('hidden.bs.modal', function () {
                    const confirmBtn = document.getElementById('confirmDeleteBtn');
                    if (confirmBtn) {
                        confirmBtn.href = '#';
                    }
                });

            } catch (e) {
                console.error('Error initializing modal:', e);
                // 降级处理：使用原生confirm
                window.confirmDelete = function(button) {
                    if (!button) return;
                    const deleteUrl = button.getAttribute('data-delete-url');
                    if (deleteUrl && confirm('确定要删除这个用户吗？此操作无法撤销。')) {
                        window.location.href = deleteUrl;
                    }
                };
            }
        }

        // 自动隐藏提示消息
        const alerts = document.querySelectorAll('.alert:not(.alert-info)');
        if (alerts.length > 0) {
            setTimeout(function() {
                alerts.forEach(function(alert) {
                    try {
                        const bsAlert = new bootstrap.Alert(alert);
                        bsAlert.close();
                    } catch (e) {
                        alert.style.display = 'none';
                    }
                });
            }, 3000);
        }
    });
</script>
{% endblock %}